import cPickle
import optparse
import os
import sys

import tables

from charmicat import BadCommandLineError

def main():
    '''
    python -m batchcat.run.filter module_name input_file rootdir cut1 [cut2 [...]]

    Batch-processing module for `bcat_filter.py'
    '''

    op = optparse.OptionParser()

    op.add_option("-z", dest='complevel', type='int', default=1,
                  help="Set output compression level 0-9", metavar='0-9')

    opts, args = op.parse_args()

    try:
        module_name = args.pop(0)
    except IndexError:
        msg = "Please supply the analysis module name, an input file,"
        msg += " the root output directory, and at least one cut name."
        raise BadCommandLineError(msg, -1)

    try:
        paths_file = args.pop(0)
    except IndexError:
        msg = "Please supply an input file, the root output directory, and at least one cut name."
        raise BadCommandLineError(msg, -2)

    with open(paths_file) as fp:
        input_files = cPickle.load(fp)

    try:
        rootdir = args.pop(0)
    except IndexError:
        msg = "Please supply the root output directory, and at least one cut name."
        raise BadCommandLineError(msg, -3)

    if len(args) == 0:
        msg = "Please supply at least one cut to apply to the input file."
        raise BadCommandLineError(msg, -4)
        
    try:
        module = __import__(module_name)           
    except ImportError:
        msg = "Error importing module `{0}'".format(module_name)
        raise charmicat.BadCommandLineError(msg, -2)

    cut_list = [module.cuts[nm] for nm in args]

    cutdir = rootdir
    for i, cut in enumerate(cut_list):
        print cut.name
        cutdir = os.path.join(cutdir, cut.name)
        os.chdir(cutdir)

        cut.prepare(cutdir, opts)
   
        try:
            cut.downstream_index = cut_list[i+1].pos_str
        except IndexError:
            pass

        output_files = []
        for ip, path in enumerate(input_files):
            sys.stdout.write("  {0}/{1} files complete\r".format(ip, len(input_files)))
            sys.stdout.flush()
                     
            output_files.append(cut.process(path))
        
        print "  {0}/{0} files complete\r".format(len(input_files))

        input_files = output_files
    
if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
